package org.molamil.acto.ext.ga {

	import com.google.analytics.AnalyticsTracker;
	import com.google.analytics.GATracker;

	import org.molamil.acto.app.AbstractApp;
	import org.molamil.acto.pages.PagesEvent;
	import org.molamil.acto.utils.StringUtils;

	public class GAController {


		// CONSTANTS
		
		public static const MODE_BRIDGE:String = "Bridge";
		public static const MODE_AS3:String = "AS3";
		
		
		// PROPERTIES
		
		// Configuration.
		public var mode:String = MODE_BRIDGE;
		public var account:String = "";
		public var visualDebug:Boolean = false;
		
		private static var _tracker:AnalyticsTracker;
		private var _app:AbstractApp;
		
		
		// CONTRUCTOR
		
		public function GAController(app:AbstractApp) {
			_app = app;
		}
		
		
		// PUBLIC METHODS
		
		public function init():void {
			var isSet:Boolean = false;
			try {
				_tracker = new GATracker(_app.session.root, account, mode, visualDebug);
				isSet = true;
			} catch (e:Error) {
				mode = MODE_AS3;
				if (account != null && StringUtils.trim(account) != "") {
					_tracker = new GATracker(_app.session.root, account, mode, visualDebug);
					isSet = true;
				}
			}
			if (isSet){
				_app.addEventListener(PagesEvent.PAGE_DISPLAY, pageDisplayHandler);
				_app.addEventListener(PagesEvent.BLOCK_DISPLAY, pageDisplayHandler);
			}
		}
		
		public static function trackPageView(pageURL:String):void {
			_tracker.trackPageview(pageURL);
		}
		
		public static function trackEvent(category:String, action:String, label:String = null, value:Number = NaN):Boolean {
			return _tracker.trackEvent(category, action, label, value);
		}
		
		
		// EVENT HANDLERS
		
		private function pageDisplayHandler(event : PagesEvent) : void {
			if (event.context.props.hasOwnProperty('trackingId')){
				_tracker.trackPageview(event.context.props.trackingId);
			}
		}


	}
	
}